import { ref, onMounted, onBeforeUnmount } from "vue";

function useMousePosition() {

    /* 定义状态 */
    const x = ref(0);
    const y = ref(0);

    /* 定义mousemoveHandler */
    const mousemoveHandler = (e) => {
        console.log("mousemoveHandler");
        x.value = e.pageX;
        y.value = e.pageY;
    };

    /* 组件挂载时侦听页面的鼠标移动事件 */
    onMounted(() => {
        document.addEventListener("mousemove", mousemoveHandler);
    });

    /* 组件卸载前移出mousemoveHandler */
    onBeforeUnmount(() => {
        document.removeEventListener("mousemove", mousemoveHandler);
        console.log("mousemoveHandler已移除");
    });

    return { x, y }
}

export default useMousePosition